package com.tianqu.tms.www.financia.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

import com.tianqu.tms.core.base.Logger;
import com.tianqu.tms.core.base.TmsController;
import com.tianqu.tms.core.base.TxController;
import com.tianqu.tms.core.base.UserContext;
import com.tianqu.tms.core.exception.TmsException;
import com.tianqu.tms.core.exception.TransactionException;
import com.tianqu.tms.core.security.TmsUserProfile;
import com.tianqu.tms.core.util.CopyFile;
import com.tianqu.tms.core.util.ImageUtils;
import com.tianqu.tms.core.util.Registry;
import com.tianqu.tms.core.util.StringUtil;
import com.tianqu.tms.core.util.TmsConstants;
import com.tianqu.tms.core.webservice.weichat.api.MobileMessage;
import com.tianqu.tms.core.webservice.weichat.api.PullingExecutor;
import com.tianqu.tms.core.webservice.weichat.api.rpc.TransferDataSyn1305Bo;
import com.tianqu.tms.dto.TmsFinanciaDto;
import com.tianqu.tms.dto.TmsMarketCarFinancialDto;
import com.tianqu.tms.entity.Car;
import com.tianqu.tms.entity.CarImage;
import com.tianqu.tms.entity.Sequence;
import com.tianqu.tms.entity.TmsFinancial;
import com.tianqu.tms.entity.User;
import com.tianqu.tms.www.financia.viewhelper.FinanciaCarInputViewHelper;
import com.tianqu.tms.www.financia.viewhelper.FinanciaCompanyInputViewHelper;

public class FinanciaCarCreationResultController extends TmsController {
	private Logger logger = Logger.getLogger(FinanciaCarCreationResultController.class);

	private static final String IMGLIST = "imgList";// 图片list
	private static final String SYSPATH = "sysPath";//
	public static final String FLOORSFLAG = "floorsflag";

	@Override
	public void execute(UserContext uc) throws Exception {
		logger.debug(this.getClass().getName() + "#execute was called.");
		TxController controller = TxController.getTxController();

		// 添加事务提交异常捕获
		try {
			controller.begin();
			// 从uc中获取会员信息
			FinanciaCarInputViewHelper viewhelp = (FinanciaCarInputViewHelper) uc.getAttribute(TmsConstants.VIEWHELP);
			uc.removeAttribute(TmsConstants.VIEWHELP);// 清空uc
			
			TmsFinancial financial = TmsFinancial.getInstance();
			TmsMarketCarFinancialDto dto = new TmsMarketCarFinancialDto();
			//view to dto
			BeanUtils.copyProperties(dto, viewhelp); 
			List<CarImage> imgList = new ArrayList<CarImage>();
			if (uc.getAttribute(IMGLIST) != null) {
				imgList = (List<CarImage>) uc.getAttribute(IMGLIST);
			}
			if (imgList != null) {
				for (int i = 0; i < imgList.size(); i++) {
					CarImage entity = (CarImage) imgList.get(i);
					if (entity.getImgKey().equals(TmsConstants.ONE)) {
						dto.setReportPhoto(entity.getImgPath());
					}
					if (entity.getImgKey().equals(TmsConstants.TWO)) {
						dto.setMaterialImages1(entity.getImgPath());
					}
					if (entity.getImgKey().equals(TmsConstants.THREE)) {
						dto.setMaterialImages2(entity.getImgPath());
					}
					if (entity.getImgKey().equals(TmsConstants.FIVE)) {
						dto.setMaterialImages3(entity.getImgPath());
					}
				}
			}
			
			//
			TmsUserProfile profile = uc.getUserProfile();
			dto.setUpdateUserId(profile.getUniqueId());
			dto.setInsertUserId(profile.getUniqueId());
			
			//
			Car car = Car.getInstance().findCarByVin(viewhelp.getVin());
			Sequence sequence = Sequence.getInstance();
			dto.setSerial(car.getSerial());
			//将image图片信息放到服务器上
			File outFile = null;
			File inFile = null;
			String sysPath = (String) uc.getAttribute(SYSPATH);
			sysPath = sysPath.replace("/tmsweb", TmsConstants.BLANK);

			try {
				if(dto.getReportPhoto()!=null && !"".equals(dto.getReportPhoto()))
				{
					inFile = new File(sysPath+dto.getReportPhoto());
					outFile = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getSerial()+"/")+dto.getSerial()+"_1.jpg");
					CopyFile.copy(inFile, outFile);	
					dto.setReportPhoto(imgPath(dto.getReportPhoto(), dto.getSerial(), "1"));
				}
				
				if(dto.getMaterialImages1()!=null && !"".equals(dto.getMaterialImages1()))
				{
					inFile = new File(sysPath+dto.getMaterialImages1());
					outFile = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getSerial()+"/")+dto.getSerial()+"_2.jpg");
					CopyFile.copy(inFile, outFile);	
					dto.setMaterialImages1(imgPath(dto.getMaterialImages1(), dto.getSerial(), "2"));
				}
				
				if(dto.getMaterialImages2()!=null && !"".equals(dto.getMaterialImages2()))
				{
					inFile = new File(sysPath+dto.getMaterialImages2());
					outFile = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getSerial()+"/")+dto.getSerial()+"_3.jpg");
					CopyFile.copy(inFile, outFile);	
					dto.setMaterialImages2(imgPath(dto.getMaterialImages2(),dto.getSerial(), "3"));
				}
				
				if(dto.getMaterialImages3()!=null && !"".equals(dto.getMaterialImages3()))
				{
					inFile = new File(sysPath+dto.getMaterialImages3());
					outFile = new File(ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getSerial()+"/")+dto.getSerial()+"_5.jpg");
					CopyFile.copy(inFile, outFile);	
					dto.setMaterialImages3(imgPath(dto.getMaterialImages3(), dto.getSerial(), "5"));

				}
			} catch (Exception e) {
				logger.error("",e);
			}
			if(dto.getId() > 0) {
				financial.updateTmsMarketCarFinancial(dto);
				dto = financial.getTmsMarketCarFinancial(dto.getId()+"");
			}else {
				dto.setStatus(1);
				dto.setFinanciaIdSerial(sequence.getSerial(8));
				financial.insertTmsMarketCarFinancial(dto);
			}
 
			logger.debug(this.getClass().getName() + "#execute was completed.");
			controller.commit();
			
			
			//微信同步
			MobileMessage message = new MobileMessage();
			message.putValue("serial", dto.getSerial());
			message.setMessage("金融车辆调用接口失败,商户ID为#serial#");
			
			
			String img1 = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getSerial()+"/")+dto.getSerial()+"_1.jpg";
			String img2 = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getSerial()+"/")+dto.getSerial()+"_2.jpg";
			String img3 = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getSerial()+"/")+dto.getSerial()+"_3.jpg";
			String img4 = ImageUtils.getImageDirectoryPath(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY)+dto.getSerial()+"/")+dto.getSerial()+"_5.jpg";
			String reportPhoto = !StringUtil.isNullOrBlank(dto.getReportPhoto())?ImageUtils.transPicToStr(img1):"";
			String materialImages1 = !StringUtil.isNullOrBlank(dto.getMaterialImages1())?ImageUtils.transPicToStr(img2):"";
			String materialImages2 = !StringUtil.isNullOrBlank(dto.getMaterialImages2())?ImageUtils.transPicToStr(img3):"";
			String materialImages3 = !StringUtil.isNullOrBlank(dto.getMaterialImages3())?ImageUtils.transPicToStr(img4):"";
			
			TransferDataSyn1305Bo api = new TransferDataSyn1305Bo();
			api.setSerial(dto.getSerial());
			api.setFinancialSerial(dto.getFinanciaIdSerial());
			api.setFinanciaId(dto.getFinanciaId());
			api.setMemberId(dto.getMemberId());
			api.setStatus(dto.getStatus());
			api.setRegisterStatus(car.getRegisterStatus());
			api.setBarCodeNum(car.getBarCodeNum());
			api.setLicensePlate(car.getLicensePlate());
			api.setVin(car.getVin());
			api.setAttestStatus(car.getAttestStatus());
			api.setReportPhoto(reportPhoto);
			api.setValuations(dto.getValuations());
			api.setLoanLimit(dto.getLoanLimit());
			api.setStartDate(dto.getStartDate());
			api.setEndDate(dto.getEndDate());
			api.setMaterialImages1(materialImages1);
			api.setMaterialImages2(materialImages2);
			api.setMaterialImages3(materialImages3);
			api.setRemark(dto.getRemark());
			api.setInsertTime(dto.getInsertTime());
			api.setInsertUserId(dto.getInsertUserId());
			api.setUpdateTime(dto.getUpdateTime());
			api.setUpdateUserId(dto.getUpdateUserId());
			api.setMarketNo(TmsConstants.MARKET_NO);
			api.setTempLicensePlate(viewhelp.getTempLicensePlate());
			PullingExecutor.getInstance().submit(api);
		} catch (Exception e) {
			try {
				controller.rollback();
			} catch (TransactionException e1) {
				throw new TmsException(TmsException.DB_TXCRROR, e1);
			}
			// 系统异常
			if (e instanceof TmsException) {
				throw e;
			}
			throw new TmsException(TmsException.DB_TXCRROR, e);
		}

	}
	
	/**
	 * 图片名称的取得
	 * 
	 * @param imagePath 图片路径
	 * @return
	 */
	private String getImageName(String imagePath){
		if(StringUtil.isNullOrBlank(imagePath)) return "";
		return imagePath.substring(imagePath.lastIndexOf("/")+1);
	}
	/**
	 * 处理存入数据库中的图片路径
	 */
	private String imgPath(String path,String memberId,String imgKey){
		return ImageUtils.getImageUrl(Registry.getConfig(TmsConstants.UPLOAD_FINANCIA_PATCH_KEY) +memberId+"/"+memberId+"_"+imgKey+".jpg") ;	
	}	

	/**
	 * 将viewhelp中的数据set到user中进行添加
	 * 
	 */
	private User setUserFormView(User entity, FinanciaCompanyInputViewHelper view) {

		entity.setLoginId(view.getUserId());
		entity.setRealName(view.getFinanciaName());
		entity.setPassword(view.getPassword());
		return entity;
	}
}
